/**
 * \brief Game mode manager will handle the overhead of game moddes
 * It will be responsible for updating and changing states
 * Please note that when ChangeGameMode is called, it is not an instant switch
 * 		The state is flagged for shutdown and shuts down when it can
 */

using System;
using UnityEngine;
using System.Collections.Generic;

namespace KaoticSSB.GameModes
{
	public class GameModeManager : MonoBehaviour
	{
		public static string[] SupportedGameModes = { "Vs.", "Vs. AI" };
		public static string SelectedGameType = "Vs. AI";

		void Start () 
		{
			print ("game mode manager");
			mCurrentGameMode = null;
			if(SelectedGameType != "")
			{
				AttemptToChangeGameMode(SelectedGameType);
			}
		}

		/*
		 * \brief Update function for game modes, gets called once a frame
		 */
		public void Update() 
		{ 
			if(mCurrentGameMode == null || mCurrentGameMode.ShouldShutdown())
			{
				SwapToQueuedGameMode();
			}
			if(mCurrentGameMode != null)
			{
				mCurrentGameMode.GameModeUpdate();
			}
		}

		/*
		 * \brief Queues up a change in the game mode
		 * IMPORTANT: This does not change the game mode immediately 
		 * This flags the state for shutdown and the game mode manager
		 * will shut the mode down when the mode says it can be shut down
		 * Does nothing if the game mode is the same as the current game mode
		 */
		public void AttemptToChangeGameMode(String gameModeName)
		{
			GameMode newMode = GetGameMode(gameModeName);
			
			//only swap modes if the intended game mode is different than the current game mode
			if(newMode != null && newMode != mCurrentGameMode)
			{
				mQueuedGameModeName = gameModeName;
				if(mCurrentGameMode != null)
				{
					mCurrentGameMode.FlagForShutdown();
				}
			}
		}

		private GameMode mCurrentGameMode;
		private String mQueuedGameModeName;

		/** These should match the entries in the Supported Game Modes */
		private GameMode GetGameMode(string gameModeName)
        {
            switch (gameModeName)
			{
				case "Vs.":
					return new GameMode_Basic();
				case "Vs. AI":
					return new GameMode_BasicAI();
				default:
					throw new Exception("Game mode " + gameModeName + " not found.");
            }
        }

		private void SwapToQueuedGameMode()
		{
			if(mQueuedGameModeName != null)
			{
				if(mCurrentGameMode != null)
				{
					mCurrentGameMode.Shutdown();
				}
	            mCurrentGameMode = GetGameMode(mQueuedGameModeName);			
				if(mCurrentGameMode != null)
				{
					mCurrentGameMode.Startup();
				}
			}
		}
	}
}

